import 'dart:async';
import 'package:BeeApp/MainPage/MainModelPage.dart';
import 'package:BeeApp/MainPage/MainSetModel.dart';
import 'package:BeeApp/MainPage/MainShowHTMLPage.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

class RegisterPage extends StatefulWidget {
  RegisterPage({Key key}) : super(key: key);

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  String yzmText = "发送验证码";
  Timer countDownTimer;
  bool check = false;
  MainSetModel mainSetModel;

  final mobileText = TextEditingController();
  final codeText = TextEditingController();
  final passWordText01 = TextEditingController();
  final passWordText02 = TextEditingController();

  @override
  void initState() {
    super.initState();
    uploadSet();
    mobileText.addListener(() {});
    codeText.addListener(() {});
    passWordText01.addListener(() {});
    passWordText02.addListener(() {});
  }

  @override
  void dispose() {
    super.dispose();
    countDownTimer?.cancel();
    mobileText?.clear();
    codeText?.clear();
    passWordText01?.clear();
    passWordText02?.clear();
  }

  void uploadSet() {
    DioUtils.noTokenPostHttp(
      context,
      "Usercommon/app_config",
      onSuccess: (t) {
        print(t);
        MainModel model = MainModel.fromJson(t);
        if (model.code == 1 && model.data != null) {
          if (mounted) {
            setState(() {
              mainSetModel = MainSetModel.fromJson(t);
            });
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  TextStyle hintStyle() {
    return TextStyle(
      fontSize: setFontSize(32),
      color: Color(0xFFCBCBCB),
    );
  }

  TextStyle textStyle() {
    return TextStyle(
      fontSize: setFontSize(32),
      color: Color(0xFF333333),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: getAppBar(context, "注册账号"),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(
                setHeight(30), setHeight(20), setHeight(30), setHeight(20)),
            child: ListView(
              children: [
                mobileView01(),
                lineView(),
                SizedBox(height: setHeight(8)),
                codeView(),
                lineView(),
                SizedBox(height: setHeight(8)),
                passwordView01(),
                lineView(),
                SizedBox(height: setHeight(8)),
                passwordView02(),
                lineView(),
                SizedBox(height: setHeight(60)),
                registerView(),
                SizedBox(height: 8),
                xieyiView(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget lineView() {
    return Container(
      height: 1,
      color: Color(0xFFEDEDED),
    );
  }

  Widget mobileView01() {
    return Container(
      color: Colors.white,
      // padding: EdgeInsets.only(left: 20, right: 20),
      child: Row(
        children: [
          SizedBox(width: setWidth(10)),
          Expanded(
              child: TextField(
            controller: mobileText,
            textAlign: TextAlign.start,
            cursorColor: Colors.grey[400], //设置光标
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "请输入手机号",
                hintStyle: hintStyle()),
            style: textStyle(),
          )),
          OutlineButton(
            onPressed: yzmText == "发送验证码" ? getCode : null,
            // padding: EdgeInsets.only(top: 0),
            borderSide: BorderSide(color: maincolor),
            highlightedBorderColor: maincolor,
            child: Text(yzmText),
            textColor: maincolor,
          ),
          SizedBox(width: setWidth(4)),
        ],
      ),
    );
  }

  void getCode() {
    if (!isPhone(mobileText.text)) {
      showToast("请输入正确的手机号");
      return;
    }
    DioUtils.postHttp(
      context,
      "user/send_code",
      parameters: {
        // "user_type": getData("AppType"),
        "mobile": mobileText.text,
        "event": "register"
      },
      onSuccess: (t) {
        if (t["code"].toString() == "1") {
          // ignore: unnecessary_statements
          yzmText == "发送验证码" ? codeGet() : null;
        }
        showToast(t["msg"]);
      },
      onError: (error) {
        print("$error");
      },
    );
  }

  void codeGet() {
    countDownTimer?.cancel(); //如果已存在先取消置空
    countDownTimer = null;
    countDownTimer = Timer.periodic(Duration(seconds: 1), (t) {
      setState(() {
        if (60 - t.tick > 0) {
          //60-t.tick代表剩余秒数，如果大于0，设置yzmText为剩余秒数，否则重置yzmText，关闭countTimer
          yzmText = "${60 - t.tick}秒";
        } else {
          yzmText = '发送验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        }
      });
    });
  }

  Widget codeView() {
    return Container(
      color: Colors.white,
      // padding: EdgeInsets.only(left: 20, right: 20),
      child: Row(
        children: [
          SizedBox(width: setWidth(10)),
          Expanded(
              child: TextField(
            controller: codeText,
            keyboardType: TextInputType.number,
            textAlign: TextAlign.start,
            cursorColor: Colors.grey[400], //设置光标
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "请输入短信验证码",
                hintStyle: hintStyle()),
            style: textStyle(),
          )),
        ],
      ),
    );
  }

  Widget passwordView01() {
    return Container(
      color: Colors.white,
      // padding: EdgeInsets.only(left: 20, right: 20),
      child: Row(
        children: [
          SizedBox(width: setWidth(10)),
          Expanded(
              child: TextField(
            obscureText: true,
            controller: passWordText01,
            textAlign: TextAlign.start,
            cursorColor: Colors.grey[400], //设置光标
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "请输入新密码",
                hintStyle: hintStyle()),
            style: textStyle(),
          )),
        ],
      ),
    );
  }

  Widget passwordView02() {
    return Container(
      color: Colors.white,
      // padding: EdgeInsets.only(left: 20, right: 20),
      child: Row(
        children: [
          SizedBox(width: setWidth(10)),
          Expanded(
              child: TextField(
            obscureText: true,
            controller: passWordText02,
            textAlign: TextAlign.start,
            cursorColor: Colors.grey[400], //设置光标
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "再次输入密码",
                hintStyle: hintStyle()),
            style: textStyle(),
          )),
        ],
      ),
    );
  }

  Widget registerView() {
    return InkWell(
      child: Container(
        alignment: Alignment.center,
        width: 900,
        height: setHeight(100),
        decoration: BoxDecoration(
          color: maincolor,
          borderRadius: BorderRadius.all(
            Radius.circular(setHeight(10)),
          ),
        ),
        child: Text(
          "注册",
          style: TextStyle(color: Colors.white, fontSize: setFontSize(34)),
        ),
      ),
      onTap: () {
        toRegister();
      },
    );
  }

  void toRegister() {
    if (!isPhone(mobileText.text)) {
      showToast("请输入正确的手机号");
      return;
    }
    if (codeText.text.length == 0) {
      showToast("验证码不能为空");
      return;
    }
    if (passWordText01.text.length < 6) {
      showToast("请输入至少6位数密码");
      return;
    }
    if (passWordText02.text != passWordText01.text) {
      showToast("请确保两次密码一致");
      return;
    }
    if (this.check == false) {
      showToast("请勾选用户协议");
      return;
    }
    showLoading(context);
    DioUtils.postHttp(
      context,
      "user/register",
      parameters: {
        // "user_type": getData("AppType").toString(),
        "mobile": mobileText.text,
        "code": codeText.text,
        "pwd": passWordText01.text,
        "repwd": passWordText02.text,
      },
      onSuccess: (t) {
        dismissLoading(context);
        print("返回数据$t");
        showToast(t["msg"]);
        if (t["code"].toString() == "1") {
          // Map userdic = t["data"]["userinfo"];
          // print(userdic["username"]);
          Navigator.pop(context);
        }
      },
      onError: (error) {
        dismissLoading(context);
        print("$error");
      },
    );
  }

  Widget xieyiView() {
    return Row(
      children: [
        InkWell(
          child: Container(
            padding: EdgeInsets.all(8),
            child: Image.asset(
              this.check
                  ? "images/MainSelectImage.png"
                  : "images/MainNoneImage.png",
              height: setHeight(40),
            ),
          ),
          onTap: () {
            setState(() {
              this.check = !this.check;
            });
          },
        ),
        SizedBox(width: 4),
        Expanded(
          child: RichText(
            text: TextSpan(
                // style: DefaultTextStyle.of(context).style,
                children: <InlineSpan>[
                  TextSpan(
                      text: '我已同意并阅读',
                      style: TextStyle(
                          color: Color(0xFFCBCBCB), fontSize: setFontSize(24))),
                  TextSpan(
                    text: '《用户协议》',
                    style: TextStyle(
                        color: Color(0xFF999999), fontSize: setFontSize(24)),
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        print('点击了回收助手用户协议');
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => MainShowHTMLPage("用户协议",
                                    mainSetModel.data.agreementPolicy)));
                      },
                  ),
                  TextSpan(
                      text: '和',
                      style: TextStyle(
                          color: Color(0xFFCBCBCB), fontSize: setFontSize(24))),
                  TextSpan(
                    text: '《隐私政策》',
                    style: TextStyle(
                        color: Color(0xFF999999), fontSize: setFontSize(24)),
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        print('点击了助手隐私政策');
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => MainShowHTMLPage("隐私政策",
                                    mainSetModel.data.agreementPolicy)));
                      },
                  ),
                ]),
          ),
        )
      ],
    );
  }
}

class SetModel {
  int code;
  String msg;
  String time;
  Data data;

  SetModel({this.code, this.msg, this.time, this.data});

  SetModel.fromJson(Map<String, dynamic> json) {
    code = json['code'];
    msg = json['msg'];
    time = json['time'];
    data = json['data'] != null ? new Data.fromJson(json['data']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['code'] = this.code;
    data['msg'] = this.msg;
    data['time'] = this.time;
    if (this.data != null) {
      data['data'] = this.data.toJson();
    }
    return data;
  }
}

class Data {
  String privacyPolicy;
  String userAgreement;
  String linkUs;
  String mobile;
  String wechat;
  String email;
  String companyAddress;

  Data(
      {this.privacyPolicy,
      this.userAgreement,
      this.linkUs,
      this.mobile,
      this.wechat,
      this.email,
      this.companyAddress});

  Data.fromJson(Map<String, dynamic> json) {
    privacyPolicy = json['privacy_policy'];
    userAgreement = json['user_agreement'];
    linkUs = json['link_us'];
    mobile = json['mobile'];
    wechat = json['wechat'];
    email = json['email'];
    companyAddress = json['company_address'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['privacy_policy'] = this.privacyPolicy;
    data['user_agreement'] = this.userAgreement;
    data['link_us'] = this.linkUs;
    data['mobile'] = this.mobile;
    data['wechat'] = this.wechat;
    data['email'] = this.email;
    data['company_address'] = this.companyAddress;
    return data;
  }
}
